/**
 * 系统名称：17173内容管理系统.
 * 作者：陈宇翔
 * (C) Copyright cyou corporation 2014  All Rights Reserved.
 * 注意： 本内容仅限于软件公司内部使用，禁止转发
 */
package cn.nubia.admin.common.springmvc;

import cn.nubia.admin.sysconfig.bean.MenuResource;
import cn.nubia.admin.sysconfig.bean.User;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * com.cyou.fz.cms.web.WebContext
 * <p>User:宇翔  copy from wj
 * <p>Date:14-5-30  下午5:45
 */
public class WebContext implements ApplicationContextAware {

    /**
     * logger对象.
     */
    private static Logger logger = LoggerFactory.getLogger(WebContext.class);

    /**
     * 注入使用的容器
     */
    private static ApplicationContext applicationContext;
    private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
    private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();

    public static final String SYS_CONFIG_CONSTANTS = "sysConfig";
    public static final String USER_CONSTANTS = "userInfo";
    public static final String USER_PERMISSION = "permission";
    public static final String MODULE_ID = "id";


    /**
     * 获取当前request
     *
     * @return
     * @author yangz
     * @date 2012-10-18 上午10:50:32
     */
    public static HttpServletRequest getRequest() {
        return request.get();
    }

    public static void setRequest(HttpServletRequest httpServletRequest) {
        request.set(httpServletRequest);
    }

    /**
     * 得到当前线程response
     *
     * @return
     * @author yangz
     * @date 2012-10-13 下午06:00:37
     */
    public static HttpServletResponse getResponse() {
        if (null == response.get()) {
            return null;
        }
        return response.get();
    }




    public static void setResponse(HttpServletResponse r) {
        response.set(r);
    }

    /**
     * 这块是系统配置,不需要放到每个用户的session中
     * @return
     */
    @Deprecated
    public static HashMap<String, String> getCachedSysConfig() {
        HashMap<String, String> map = (HashMap<String, String>) request.get().getSession().getAttribute(SYS_CONFIG_CONSTANTS);
        return map;
    }


    public static User getCachedUser() {
        User user =  (User)getAttr(USER_CONSTANTS);
        return user;
    }

    public static String getRefer(){
        return request.get().getHeader("Referer");
    }

    public static Object getAttr(String key){
        Object value = null;
        try{
            HttpSession session = request.get().getSession();
            if (session == null) {
                return null;
            }
            value = session.getAttribute(key);
        }catch (UnknownSessionException|IllegalStateException e ){
            logger.error("session 过期了!" , e);
            request.get().getSession(true);
        }
        return value;
    }


    public static Integer getCachedUserId(){
        User user = getCachedUser();
        if (user == null) {
            return null;
        }
        return user.getId();
    }


    public static void setToCache(String key, Object object) {
        request.get().getSession().setAttribute(key, object);
    }


    public static void setPermissionToCache(Set<MenuResource> permissionToCache) {
        Map<String ,Boolean> permissionMap = new HashMap<>();
        for(MenuResource resource:permissionToCache){
            String permission = "";
            String[] permisstions = resource.getPermission().split(":");
            for(String perm : permisstions){
                permission = "".equals(permission)?perm:permission+":"+perm;
                permissionMap.put(permission,true);
            }
        }
        setToCache(USER_PERMISSION, permissionMap);
    }

    public static void deleteCache(String key) {
        request.get().getSession().removeAttribute(key);
    }

    public static Map<String,Boolean> getPermission(){
        return (Map<String ,Boolean> )getAttr(USER_PERMISSION);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        WebContext.applicationContext = applicationContext;
    }

    public static void remove() {
        request.remove();
        response.remove();
    }


}
